package com.xiaoxin.yixinai.wx;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.marker.weixin.DefaultSession;
import org.marker.weixin.HandleMessageAdapter;
import org.marker.weixin.MySecurity;
import org.marker.weixin.msg.Msg4Event;
import org.marker.weixin.msg.Msg4Image;
import org.marker.weixin.msg.Msg4Link;
import org.marker.weixin.msg.Msg4Location;
import org.marker.weixin.msg.Msg4Text;
import org.marker.weixin.msg.Msg4Video;
import org.marker.weixin.msg.Msg4Voice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaoxin.yixinai._frame.base.BaseController;
import com.xiaoxin.yixinai._frame.utils.StringUtils;
import com.xiaoxin.yixinai.activity.wxuser.WxUser;

@Controller
@RequestMapping("/wx")
public class WxController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(WxController.class);
	
	private static String appid = "wxa9055239916bb60c";
	private static String appsecret = "3b21b8977e6515924d5bd5ea0ef795c2";
	private static String token = "554c3f156d494a7f81e52db96105c734";
	private static String encodingaeskey = "XutAh3uqSWL3YXn11kw3wQOcnSTqJxWUdxjsrKTLqJ4";
	
	
	@Resource
	WxService wxCompanyUserService;
	
	/**
	 * 接口验证,总入口
	 * @param out
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	 @RequestMapping(value="/accept")
	 public void accept(
			 PrintWriter out,
			 HttpServletRequest request,
			 HttpServletResponse response
			 ) throws Exception{     
		try{
			logger.info("微信接口");
			String signature = request.getParameter("signature");		//微信加密签名
			String timestamp = request.getParameter("timestamp");		//时间戳
			String nonce	 = request.getParameter("nonce");			//随机数
			String echostr 	 = request.getParameter("echostr");			//字符串
			
			if(null != signature && null != timestamp && null != nonce && null != echostr){
				logger.info("进入身份验证");
			    List<String> list = new ArrayList<String>(3) { 
		    		private static final long serialVersionUID = 2621444383666420433L; 
			    	public String toString() {  // 重写toString方法，得到三个参数的拼接字符串
		               return this.get(0) + this.get(1) + this.get(2); 
			    	} 
			    }; 
			    list.add(token); 		//读取Token(令牌)
			    list.add(timestamp); 
			    list.add(nonce); 
			    Collections.sort(list);							// 排序 
			    String tmpStr = new MySecurity().encode(list.toString(), 
			    MySecurity.SHA_1);								// SHA-1加密 
			   
			    if (signature.equals(tmpStr)) { 
			    	out.write(echostr);						// 请求验证成功，返回随机码 
			    }else{ 
			    	out.write(""); 
			    } 
			    out.flush();
				out.close(); 
			}else{ 
				logger.info("进入消息处理");
				response.reset();
				sendMsg(request,response);
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
	}
	 
	 /**
	  * 处理微信服务器发过来的各种消息，包括：文本、图片、地理位置、音乐等等 
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 public void sendMsg(HttpServletRequest request, HttpServletResponse response) throws Exception{ 

         InputStream is = request.getInputStream(); 
         OutputStream os = response.getOutputStream(); 

         final DefaultSession session = DefaultSession.newInstance(); 
         session.addOnHandleMessageListener(new HandleMessageAdapter(){ 
        	 
        	/**
        	 * 事件
        	 */
        	@Override
        	public void onEventMsg(Msg4Event msg) {
        		/** msg.getEvent()
        		 * unsubscribe：取消关注 ; subscribe：关注
        		 */
        		if("subscribe".equals(msg.getEvent())){
        			returnMSg(msg,null,"关注");
        		}
        	}
        	
			/**
			 * 收到的文本消息
			 */
			@Override 
			public void onTextMsg(Msg4Text msg) { 
			   returnMSg(null,msg,msg.getContent().trim());
			}
			
			@Override
        	public void onImageMsg(Msg4Image msg) {
        		super.onImageMsg(msg);
        	}
        	 
        	 @Override
        	public void onLocationMsg(Msg4Location msg) {
        		super.onLocationMsg(msg);
        	}
        	 
        	@Override
        	public void onLinkMsg(Msg4Link msg) {
        		super.onLinkMsg(msg);
        	}
        	
        	@Override
        	public void onVideoMsg(Msg4Video msg) {
        		super.onVideoMsg(msg);
        	}
        	
        	@Override
        	public void onVoiceMsg(Msg4Voice msg) {
        		super.onVoiceMsg(msg);
        	}
        	
        	@Override
        	public void onErrorMsg(int errorCode) {
        		super.onErrorMsg(errorCode);
        	}
        	
        	/**
        	 * 返回消息
        	 * @param emsg
        	 * @param tmsg
        	 * @param getmsg
        	 */
        	public void returnMSg(Msg4Event emsg, Msg4Text tmsg, String getmsg){
                 String toUserName,fromUserName,createTime;
                 if(null == emsg){
                	 toUserName = tmsg.getToUserName();
                	 fromUserName = tmsg.getFromUserName();
                	 createTime = tmsg.getCreateTime();
                 }else{
                	 toUserName = emsg.getToUserName();
                	 fromUserName = emsg.getFromUserName();
                	 createTime = emsg.getCreateTime();
                 }
                 Msg4Text rmsg = new Msg4Text(); 
				 rmsg.setFromUserName(toUserName); 
				 rmsg.setToUserName(fromUserName); 
				 //rmsg.setFuncFlag("0"); 
				 rmsg.setContent("关键词暂无匹配，智能小赢，正在学习中..."); //回复文字消息
				 session.callback(rmsg); 
        	}
        	
        }); 

         /*必须调用这两个方法   如果不调用close方法，将会出现响应数据串到其它Servlet中。*/ 
         session.process(is, os);	//处理微信消息  
         session.close();			//关闭Session 
     }
	
	@RequestMapping(value = "/authorize", method = RequestMethod.GET)
	public void authorize(WxParams wxInfoParams) throws Exception{
		try {
			//微信授权码
			String code = request.getParameter("code");
			if(StringUtils.isEmpty(code)){
				StringBuffer back = request.getRequestURL();
				if(request.getQueryString()!=null) 
					back.append("?").append(request.getQueryString());
				String url = wxCompanyUserService.getAuthorizeURL(appid, back.toString(), "snsapi_userinfo");
				response.sendRedirect(url);
				return;
			}
			
			if(code != null && code.length() > 0){
				Integer activityId = Integer.valueOf(request.getParameter("activityId"));
				Integer parentId = Integer.valueOf(request.getParameter("parentId"));
				WxUser wxuser = wxCompanyUserService.doAuthorizeAction(appid,appsecret,code,activityId,parentId);
				if(wxuser == null){
					throw new Exception();
				}
				request.getSession().setAttribute("wxuser", wxuser);
				StringBuffer back = request.getRequestURL();
				String basePath = back.delete(back.length() - request.getRequestURI().length(), back.length()).append("/").toString(); 
				String toUrl = basePath + "/wx/activity/index";
				if(request.getQueryString()!=null) 
					toUrl+="?"+request.getQueryString();
//				if(toUrl.indexOf("?")>0) {
//					toUrl+="&openid="+openid;
//				}else {
//					toUrl+="?openid="+openid;
//				}
				response.sendRedirect(toUrl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
